//
//  RegisterDetailInfo_Vm.swift
//  MikerShop
//
//  Created by eme on 2016/11/26.
//  Copyright © 2016年 eme. All rights reserved.
//


import RxSwift
import Result
import SwiftyJSON
import NetWorkCore
import ModelProtocol
import UtilCore
import BrandonCore
/*
 owner:cy
 update:2016年11月26日14:54:31
 info: 提交详细资料viewmodel
 */
class RegisterDetailInfo_Vm {
    
    let validatedqymc: Observable<ValidationResult>
    let validatedlxr: Observable<ValidationResult>
    let validatedyyzzbh: Observable<ValidationResult>
    let addressVariable = Variable<Bool>(false)
    let splicenseurlVariable = Variable<Bool>(false)
    /// 获取填写的资料信息
    let getshopSubject = PublishSubject<String>()
    let getshopSuccess = PublishSubject<GlShopModel>()
    // 表示btn 是否可以点击状态
    let signupEnabled: Observable<Bool>
    // Is signing process in progress
    let signingIn: Observable<Bool>
    private let disposeBag = DisposeBag()
    let error = PublishSubject<MikerError>()
    let submitSuccess = PublishSubject<UserModel>()
    private var isValidated:(isOk:Bool ,error:String) = (true,"")
    
    init(input: (
        qymc: Observable<String>,
        lxr: Observable<String>,
        yyzzbh: Observable<String>,
        submitTaps: Observable<GlShopModel>
        ),
         validationService: RegisterValidationProtocol
        ) {
        validatedqymc = input.qymc.map{ companyName in
            return validationService.validateCompanyName(companyName)
            }.shareReplay(1)
        
        validatedlxr = input.lxr.map{ contactName in
            return validationService.validateContactName(contactName)
            }.shareReplay(1)
        validatedyyzzbh = input.yyzzbh.map{ bslicense in
            return validationService.validateBslicense(bslicense)
            }.shareReplay(1)
    
        let inputObservables = Observable.combineLatest(input.qymc, input.lxr,input.yyzzbh,input.submitTaps) { ($0, $1,$2,$3) }
        
        let signingIn = ActivityIndicator()
        self.signingIn = signingIn.asObservable()
        self.signupEnabled = Observable.combineLatest(
            validatedqymc,
            validatedlxr,
            addressVariable.asObservable(),
            validatedyyzzbh,
            splicenseurlVariable.asObservable(),
            signingIn.asObservable()
        ){ qymc, lxr ,address,validatedyyzzbh,splicenseurl,signingIn in
            qymc.notEmpty && lxr.notEmpty && address && validatedyyzzbh.notEmpty && splicenseurl && !signingIn
            }
            .distinctUntilChanged()
            .shareReplay(1)
        input.submitTaps
            .filter{ _ in
                return !self.isValidated.isOk
            }
            .subscribe(onNext: {[unowned self] (_) in
                 self.error.onNext(MikerError("文本录入错误", code: 601, message: self.isValidated.error))
            })
            .addDisposableTo(disposeBag)
        input.submitTaps.filter{ _ in
            return self.isValidated.isOk
            }.withLatestFrom(inputObservables)
            .map{ qymc , lxr ,yyzzbh,glShop -> UserApi in
                glShop.splicense = yyzzbh
                glShop.spcontact = lxr
                glShop.spcompany = qymc
                return UserApi.saveAuthInfo(glshop:JSONHelper.parseToJson(glShop.dictionaryRepresentation() as AnyObject))
            }
            .emeRequestApiForObj(UserModel.self, activityIndicator: signingIn)
            .subscribe(onNext: {[unowned self] (result) in
                switch result {
                case .success(let data):
                    self.submitSuccess.onNext(data)
                case .failure(let error):
                    self.error.onNext(error)
                }
            })
            .addDisposableTo(disposeBag)
        Observable.combineLatest(
            validatedqymc,
            validatedlxr,
            validatedyyzzbh,
            addressVariable.asObservable(),
            splicenseurlVariable.asObservable()
        ) { (item1, item2,item3,address,splicenseurl) -> (isOk:Bool ,error:String) in
            
            if !item1.isValid{
                return (false,item1.message)
            }
            if !item2.isValid{
                return (false,item2.message)
            }
            if !address{
                return (false,"请选择所在城市")
            }
            if !item3.isValid{
                return (false,item3.message)
            }
            if !splicenseurl{
                return (false,"请上传营业执照照片")
            }
            return (true,"")
            }
            .subscribe(onNext: { [unowned self] (item) in
                self.isValidated = item
            })
            .addDisposableTo(disposeBag)
        
        self.getshopSubject
            .map{spid in  return UserApi.getshop(spid: spid) }
            .emeRequestApiForObj(GlShopModel.self)
            .subscribe(onNext: {[unowned self] (result) in
                switch result {
                case .success(let data):
                    self.getshopSuccess.onNext(data)
                case .failure(let error):
                    self.error.onNext(error)
                }
            })
            .addDisposableTo(disposeBag)
        
    }
    
}
